package o2o.business.image;

import sun.misc.BASE64Decoder;

import java.io.*;

public class Base64ToImageUtils {

    public static InputStream GenerateInputStream(String imgStr) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            InputStream in = new ByteArrayInputStream(bytes);

            return in;
        } catch (Exception e) {
            return null;
        }
    }

    public synchronized static boolean GenerateImage(String imgStr, String path) throws IOException, BigImageException {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        if (imgStr.startsWith("data:image")) {
            imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
        }
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] bytes = decoder.decodeBuffer(imgStr);
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {        // 调整异常数据
                bytes[i] += 256;
            }
        }
        //判断大小
        if (bytes.length >= 4 * 1024 * 1024) {
            throw new BigImageException("图片大小不能超过4M");
        }
        System.out.println(bytes.length);
        // 生成jpeg图片
        System.out.println("路径：" + path);
        OutputStream out = new FileOutputStream(path);
        out.write(bytes);
        out.flush();
        out.close();

        return true;
    }

    public static void main(String[] args) {
        String str = "";
        try {
            GenerateImage(str, "asd.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BigImageException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
